package com.zghhost.simplehttp.core;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Window extends JFrame{
	private static final long serialVersionUID = 2719389678614529550L;
	
	JTextField addressInput;
	JTextField tokenInput;
	JTextArea reqBodyInput;
	
	JButton actionBtn;
	
	JTextArea resBodyText;
	
	JPanel method;
	JComboBox<String> methodBox;
	
	public Window(String name){
		super(name);
		this.setSize(828, 600);
		this.setLayout(null);
		setCentered();
		ifWindowClosed();
		
		addLabel("请求地址：", 5, 5, 80, 22);
		addLabel("Token（非必须）：", 5, 32, 140, 22);
		addLabel("RequestBody：", 5, 54, 120, 22);
		
		method=new JPanel();
		method.setBounds(80, -3, 70, 56);
		methodBox=new JComboBox<String>();
		methodBox.addItem("POST");
		methodBox.addItem("GET");
		method.add(methodBox);
	    this.add(method);
		
		addressInput = new JTextField();
		addressInput.setBounds(150, 5, 657, 22);
		this.add(addressInput);
		
		tokenInput = new JTextField();
		tokenInput.setBounds(150, 32, 657, 22);
		this.add(tokenInput);
		
		JPanel reqPanel = new JPanel();
		reqBodyInput = new JTextArea();
//		reqBodyInput.setBounds(5, 80, 800, 100);
		reqBodyInput.setText("{}");
		reqPanel.setBounds(5, 80, 800, 100);
		reqPanel.setLayout(new BorderLayout());
		reqPanel.add(new JScrollPane(reqBodyInput));
		this.add(reqPanel);
		
		actionBtn = new JButton("提交");
		actionBtn.setBounds(725, 190, 80, 35);
		this.add(actionBtn);
		
		addLabel("ResponseBody：", 5, 220, 120, 22);
		
		resBodyText = new JTextArea();
		JPanel resPanel = new JPanel();
		resPanel.setBounds(5, 250, 800, 250);
		resPanel.setLayout(new BorderLayout());
		resPanel.add(new JScrollPane(resBodyText));
		this.add(resPanel);
		
		
		LinkLabel jsonFormatLink = new LinkLabel("JSON格式化工具","http://tool.oschina.net/codeformat/json");
		jsonFormatLink.setBounds(700, 535, 400, 22);
		this.add(jsonFormatLink);
		
		LinkLabel urlEncodeLink = new LinkLabel("URL转码工具","http://tool.oschina.net/encode?type=4");
		urlEncodeLink.setBounds(600, 535, 400, 22);
		this.add(urlEncodeLink);
		
		//提交按钮事件
		requestBtnEvent();
	}
	
	
	/**
	 * 添加一个label
	 */
	public void addLabel(String name,int x, int y, int width, int height){
		addLabel(null,name,x,y,width,height);
	}
	
	/**
	 * 添加一个label
	 */
	public void addLabel(JLabel label,String name,int x, int y, int width, int height){
		if(label == null){
			label = new JLabel(name);
		}
		label.setBounds(x, y, width, height);
		this.add(label);
	}
	
	/**
	 * 居中显示
	 */
	public void setCentered(){
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		int x = (int)(toolkit.getScreenSize().getWidth()-this.getWidth())/2;
		int y = (int)(toolkit.getScreenSize().getHeight()-this.getHeight())/2;
		this.setLocation(x, y);
	}
	
	/**
	 * 如果关闭窗口 退出虚拟机
	 */
	public void ifWindowClosed(){
		WindowAdapter closeEvent = new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(-1);
			}
		};
		this.addWindowListener(closeEvent);
	}
	
	/**
	 * 提交按钮事件
	 */
	public void requestBtnEvent(){
		actionBtn.addActionListener(new ActionListener() {
			URL url;
			HttpURLConnection connection;
			OutputStream os;
			BufferedReader remote_ret;
			
			@Override
			public void actionPerformed(ActionEvent event) {
				try {
					String address = null,token = null,body = null,method = null;
					address = addressInput.getText();
					token = tokenInput.getText();
					body = reqBodyInput.getText();
					method = methodBox.getSelectedObjects()[0].toString();
					
					if(token == null || "".equals(token)){
						token = "5e54ee3bf8585201ac14e5369269571a";
					}
					
					String encode_param_body = URLEncoder.encode(body, "utf-8");
					String sign = MD5Utils.getMD5(encode_param_body + "461de5b941e9622585cc8c184f65aef6");
					
//					String fullParam = "{\"head\":{\"partner\":\"11110001\",\"platform\":\"ANDROID\",\"net\":\"2G\",\"oemid\":\"UUID\",\"idfa\":\"1\",\"version\":\"10000\",\"phone_code\":\"iphone4\",\"token\":\""+token+"\",\"sign\":\""+sign+"\"},\"body\":"+body+"}";
					String fullParam = body;
							
					url = new URL(address);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod(method);
					
					connection.addRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
					connection.setDoOutput(true);
					connection.setDoInput(true);
					
					os = connection.getOutputStream();
					os.write(fullParam.getBytes(Charset.forName("UTF-8")));
					os.flush();
					
					remote_ret = new BufferedReader(new InputStreamReader(
							connection.getInputStream(),Charset.forName("UTF-8")));
					
					StringBuffer buffer = new StringBuffer();
					String line;
					while((line = remote_ret.readLine()) != null){
						buffer.append(line);
					}
					
					String resMsg = URLDecoder.decode(buffer.toString(), "utf-8");
					
					resBodyText.setForeground(Color.black);
					resBodyText.setText(SimpleJsonUtil.format(resMsg));
				} catch (Exception e) {
					ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
					e.printStackTrace(new java.io.PrintWriter(buf, true));
					String expMessage = buf.toString();
					try {
						buf.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					resBodyText.setForeground(Color.red);
					resBodyText.setText(expMessage);
				}finally{
					try {
						os.close();
						remote_ret.close();
						connection.disconnect();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
		});
	}
}
